<template>
  <div ref="chartRef" :style="{ height }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { useChartDataFetch } from '../composables/useChartDataFetch';

interface ChartDataItem {
  name: string;
  value: number;
}

interface ChartData {
  dataSource: {
    type: 'static' | 'api' | 'sql';
    data?: string;
    url?: string;
    method?: string;
    params?: string;
    sql?: string;
  };
  config: Record<string, any>;
}

const props = defineProps({
  chartData: {
    type: Object as () => ChartData,
    required: true
  },
  height: {
    type: String,
    default: '100%'
  }
});

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

// 获取图表数据
const { data, startFetch } = useChartDataFetch(props.chartData.dataSource);

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  chart = echarts.init(chartRef.value);
  
  // 监听容器大小变化
  const resizeObserver = new ResizeObserver(() => {
    chart?.resize();
  });
  resizeObserver.observe(chartRef.value);
  
  // 清理
  onUnmounted(() => {
    resizeObserver.disconnect();
    chart?.dispose();
  });
};

// 更新图表
const updateChart = () => {
  if (!chart || !data.value) return;
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        color: '#fff'
      }
    },
    series: [{
      name: '数据分布',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold',
          color: '#fff'
        }
      },
      labelLine: {
        show: false
      },
      data: data.value.map((item: any) => ({
        name: item.name,
        value: item.value
      }))
    }],
    ...props.chartData.config
  };
  
  chart.setOption(option);
};

// 初始化
onMounted(() => {
  initChart();
  startFetch();
});

// 监听数据变化
watch(data, () => {
  updateChart();
}, { deep: true });
</script> 